<template>
	<div>
		<navigation-bar>
			<div class="searchContent">
				<el-input
					v-model="examineeName"
					placeholder="请输入名称"
					size="mini"
					style="width: 150px; margin-right: 10px"
				></el-input>
				<custom-button
					type="search"
					style="margin-right: 10px"
					@searchClick="searchClick"
				></custom-button>
				<custom-button
					type="reset"
					style="margin-right: 10px"
					@resetClick="resetClick"
				></custom-button>
				<custom-button
					type="add"
					title="设置黑名单"
					style="margin-right: 10px"
					@addClick="setClick"
				></custom-button>
				<custom-button
					type="add"
					style="margin-right: 10px"
					@addClick="addClick"
				></custom-button>
				<custom-button
					type="add"
					@addClick="hisCodeClick"
					style="margin-right: 10px"
					title="设置HisCode"
				></custom-button>
				<custom-button
					type="print"
					@printClick="printClick"
					style="margin-right: 10px"
					title="打印标签"
				></custom-button>
				<custom-button
					type="print"
					@printClick="printBadge"
					style="margin-right: 10px"
					title="打印工牌"
				></custom-button>
				<custom-button
					type="print"
					@printClick="printWd"
					style="margin-right: 10px"
					title="打印腕带"
				></custom-button>
				<custom-button
					type="print"
					@printClick="outMedical"
					title="病历导出"
				></custom-button>
			</div>
		</navigation-bar>
		<table-index
			:dataSource="dataSource"
			:tableColumns="tableColumns"
			:btnList="btnList"
			:pageSize="pageSize"
			:pageCount="pageCount"
			:pageNo="pageNo"
			@pageChange="pageChange"
			@editRow="editRow"
			@viewRow="viewRow"
			@deleteRow="deleteRow"
			isSizes
			@handleSizeChange="handleSizeChange"
			selection
			@handleSelectionChange="handleSelectionChange"
		></table-index>
		<div v-if="dialogShow">
			<custom-dialog
				:title="dialogTitle"
				size="large"
				@dialogClose="dialogClose"
			>
				<form-index
					:formConfig="formConfig"
					@submit="submit"
					:type="type"
					@formInputChange="formInputChange"
					ref="form"
					showIdCard="true"
					@readIdCard="readIdCard"
				>
					<!--  <div>这里还可以插入其它内容进行拓展</div> -->
				</form-index>
			</custom-dialog>
		</div>
		<div v-if="dialogBlackShow">
			<custom-dialog
				title="新增受试者黑名单"
				size="large"
				@dialogClose="dialogBlackClose"
			>
				<form-index
					:formConfig="blackFormConfig"
					@submit="blackSubmit"
					type="add"
				>
					<!--  <div>这里还可以插入其它内容进行拓展</div> -->
				</form-index>
			</custom-dialog>
		</div>
		<div v-if="hisCodeShow">
			<custom-dialog
				title="设置HisCode"
				size="small"
				@dialogClose="dialogHisCodeClose"
			>
				<his-code-table></his-code-table>
			</custom-dialog>
		</div>
	</div>
</template>

<script>
	import { subjectRegistrationBlackForm } from "@/assets/form/managementCenter/subjectManagement/filteringPeriodManagement/subjectRegistrationBlackForm"
	import { subjectRegistrationForm } from "@/assets/form/managementCenter/subjectManagement/filteringPeriodManagement/subjectRegistrationForm"

	import customDialog from "@/components/customComponents/customDialog"
	import customButton from "@/components/customComponents/customForm/customButton"
	import formIndex from "@/components/customComponents/customForm/formIndex"
	import tableIndex from "@/components/customComponents/customeTable/tableIndex"
	import hisCodeTable from "@/components/customComponents/managementCenter/hisCodeTable"
	import navigationBar from "@/components/customComponents/managementCenter/navigationBar"
	import { AjaxCommon, printAddress } from "@/libs/apiCommon"
	import { CardId } from "@/libs/cardId"
	import { PopupCommon } from "@/libs/popupCommon"
	import { SessionCommon } from "@/libs/sessionCommon"
	import { Utility } from "@/libs/utility"

	var ws
	var first = true
	export default {
		components: {
			navigationBar,
			customButton,
			tableIndex,
			customDialog,
			formIndex,
			hisCodeTable,
		},
		data() {
			return {
				projectTestperiod: "",
				currentExp: "",
				isCon: false,
				rightSelectIds: [],
				hisCodeShow: false,
				examineeName: "",
				// table 相关参数  begin
				dataSource: [],
				tableColumns: [
					{
						prop: "examineeCode",
						label: "受试者编码",
						width: 120,
					},
					{
						prop: "filterNo",
						label: "筛选号",
						width: 80,
					},
					{
						prop: "hisNo",
						label: "His系统编号",
						width: 160,
					},
					{
						prop: "examineeName",
						label: "姓名",
						width: 120,
					},
					{
						prop: "examineeEn",
						label: "姓名缩写",
						width: 80,
					},
					{
						prop: "sex",
						label: "性别",
						dictName: "sex",
						width: 80,
					},
					{
						prop: "birthday",
						label: "出生日期",
						width: 100,
					},
					{
						prop: "idCard",
						label: "身份证",
						width: 180,
					},
					{
						prop: "nation",
						label: "民族",
						dictName: "nation",
						width: 100,
					},
					{
						prop: "telephone",
						label: "电话",
						width: 130,
					},
					{
						prop: "status",
						label: "状态",
						dictName: "e_status",
						width: 80,
					},
					{
						prop: "createTime",
						label: "登记时间/发放ICF时间",
					},
					{
						prop: "createByName",
						label: "登记人",
						width: 120,
					},
				],
				btnList: ["edit", "view", "delete"],
				pageSize: 20,
				pageCount: 100,
				pageNo: 1,
				// table 相关参数  end

				// 弹窗是否显示
				dialogShow: false,
				dialogBlackShow: false,
				// 弹窗标题 (新增修改不同)
				dialogTitle: "",

				// form的配置信息
				formConfig: subjectRegistrationForm,
				type: "add",
				blackFormConfig: subjectRegistrationBlackForm,
			}
		},
		beforeRouteLeave: (to, from, next) => {
			first = false
			try {
				console.log(to, from)
				if (ws) {
					ws.send(JSON.stringify({ Action: "idcard_disconnect" }))
					ws.close()
				}
			} catch (error) {
				console.log(error, "错误信息.............")
			}
			next()
		},
		methods: {
			outMedical() {
				let self = this
				if (self.rightSelectIds.length != 1) {
					PopupCommon.notify("info", "请勾选一个受试者")
					return
				}
				console.log(self.currentExp.expStatus)
				if (self.currentExp.expStatus != "ed") {
					PopupCommon.notify("info", "当前试验未完结，无法导出病历表")
					return
				}
				var url = ""
				if ("1" === self.currentExp.expIntermittent) {
          PopupCommon.notify("info", "暂无1个周期的病历导出")
          return
				} else if ("2" === self.currentExp.expIntermittent) {
					url = "/ccdc/jmreport/view/821267669346762752?"
				} else if ("3" === self.currentExp.expIntermittent) {
					url = "/ccdc/jmreport/view/821239595020402688?"
				} else if ("4" === self.currentExp.expIntermittent) {
					url = "/ccdc/jmreport/view/820825966559182848?"
				}
				var token = localStorage.getItem("token")
				var expId = self.projectTestperiod.testId
				var pmId = self.projectTestperiod.projectId
				window.open(
					url +
						"token=" +
						token +
						"&expId=" +
						expId +
						"&pmId=" +
						pmId +
						"&examineeCode=" +
						self.rightSelectIds[0].examineeCode
				)
			},
			// 读身份证
			readIdCard() {
				let self = this
				if (self.isCon) {
					// 发送识别指令
					ws.send(JSON.stringify({ Action: "idcard_read" }))
					return
				}
				// 初始化websocket连接
				ws = new WebSocket("ws://127.0.0.1:34567/ws")
				if (ws) {
					ws.onopen = function (evt) {
						console.log(evt)
						// 身份证连接
						ws.send(JSON.stringify({ Action: "idcard_connect" }))
						// 身份证读卡器状态
						ws.send(JSON.stringify({ Action: "idcard_statue" }))
						// 发送识别指令
						ws.send(JSON.stringify({ Action: "idcard_read" }))

						// 接收websocket反馈信息
						ws.onmessage = function (evt) {
							var res = JSON.parse(evt.data)
							if (res != null && res != undefined) {
								if (res.ActionResult) {
									switch (res.ResultType) {
										case "IDCard":
											var userData = res.ResultObject
											switch (res.ActionCommand) {
												case "idcard_read": // 读取身份证
													if (userData != null && userData != undefined) {
														let value = self.$refs.form.getFormValue()
														console.log(userData)
														value.examineeName = userData.Name
														value.idCard = userData.IDNum
														const born = userData.Birthdate
														value.birthday =
															born.substr(0, 4) +
															"-" +
															born.substr(4, 2) +
															"-" +
															born.substr(6, 2)
														value.sex = userData.Sex
														value.homeProvince = userData.Address
														value.homeDetailed = userData.Address

														console.log(userData.NationOrCountry)
														const nationList = Utility.getDictList("nation")
														const nation = nationList.find(
															(t) =>
																t.label.indexOf(userData.NationOrCountry) != -1
														)
														if (nation && nation.value) {
															value.nation = nation.value
														}

														const bolbItem = Utility.base64ToBlob(
															"data:image/jpg;base64," + userData.Photo
														)
														const fileItem = new File(
															[bolbItem],
															"screenshot.png",
															{
																type: "image/jpeg",
															}
														)

														Utility.xhrRequest(fileItem).then((res) => {
															// 这里只有一张照片
															value.idCardHeadUrl = res.message
															self.$refs.form.changeFormValue(
																value,
																"idCardHeadUrl"
															)
														})
													}
													break
												case "idcard_statue": // 读取设备状态
													if (userData.ConnectStatue) {
														self.isCon = true
														PopupCommon.notify(
															"info",
															"身份证读卡器连接正常，请将身份证正面放到读卡器上面，然后点击读卡按钮。"
														)
														setTimeout(() => {
															// 发送识别指令，自动发送一次读卡(有可能身份证已经放到上面了)
															ws.send(JSON.stringify({ Action: "idcard_read" }))
														}, 1000)
													} else {
														PopupCommon.notify("info", "身份证读卡器未连接")
													}
													break
												case "idcard_connect": // 连接读卡器
												case "idcard_disconnect": // 断开读卡器
												default:
													console.log("操作成功<br/>")
													break
											}
											break
										default:
											break
									}
								}
							}
						}
					}
					ws.onclose = function (evt) {
						console.log(evt, "evt.........")
						if (first) {
							PopupCommon.notify("info", "服务未运行，请手动以管理员身份运行。")
						}
					}
				}
			},
			handleSelectionChange(d) {
				this.rightSelectIds = d
			},
			handleSizeChange(e) {
				this.pageSize = e
				this.initPage()
			},
			printBadge() {
				let urlAdd = `${printAddress}/ccdc/jmreport/view/805746513617199104
?token=${localStorage.getItem("token")}`

				if (this.rightSelectIds.length > 0) {
					let ids = this.rightSelectIds
						.map((t) => {
							return t.examineeCode
						})
						.join(",")
					if (this.rightSelectIds.length > 0) {
						urlAdd += "&examineeCode=" + ids
					}
				}
				let projectTestperiod =
					window.sessionStorage.getItem("projectTestperiod")
				if (projectTestperiod) {
					projectTestperiod = JSON.parse(projectTestperiod)
					urlAdd += `&pmId=${projectTestperiod.projectId}&expId=${projectTestperiod.testId}`
				}

				console.log(urlAdd)
				window.open(urlAdd)
			},
			printClick() {
				let urlAdd = `${printAddress}/ccdc/tmrreport/pdf/show?1=1&_u=file:shoushizheV1.tmrreport.xml&_i=1&_r=1
`

				if (this.rightSelectIds.length > 0) {
					let ids = this.rightSelectIds
						.map((t) => {
							return t.examineeCode
						})
						.join(",")
					if (this.rightSelectIds.length > 0) {
						urlAdd += "&examineeCode=" + ids
					}
				}
				let projectTestperiod =
					window.sessionStorage.getItem("projectTestperiod")
				if (projectTestperiod) {
					projectTestperiod = JSON.parse(projectTestperiod)
					urlAdd += `&pmId=${projectTestperiod.projectId}&expId=${projectTestperiod.testId}`
				}

				console.log(urlAdd)
				window.open(urlAdd)
			},
			printWd() {
				let urlAdd = `${printAddress}/ccdc/tmrreport/pdf/show?1=1&_u=file:wandaibqV1.tmrreport.xml&_i=1&_r=1`

				if (this.rightSelectIds.length > 0) {
					let ids = this.rightSelectIds
						.map((t) => {
							return t.examineeCode
						})
						.join(",")
					if (this.rightSelectIds.length > 0) {
						urlAdd += "&examineeCode=" + ids
					}
				}
				let projectTestperiod =
					window.sessionStorage.getItem("projectTestperiod")
				if (projectTestperiod) {
					projectTestperiod = JSON.parse(projectTestperiod)
					urlAdd += `&pmId=${projectTestperiod.projectId}&expId=${projectTestperiod.testId}`
				}

				console.log(urlAdd)
				window.open(urlAdd)
			},

			formInputChange(e) {
				if (e.filedName == "idCard") {
					const data = CardId.getInfoByCardId(e.value)
					if (data) {
						let newData = e.allData
						newData["birthday"] = data.birthday
						console.log(data, "...")
						newData["sex"] = data.sex
						this.$refs.form.changeFormValue(newData)
					}
				}
			},
			blackSubmit(d) {
				console.log(d)
				let self = this
				delete d.id
				AjaxCommon("/ccdc/black/add", "post", d)
					.then((res) => {
						if (res.data.code == 200) {
							PopupCommon.notify("success", res.data.message)
							self.initPage()
							self.dialogBlackClose()
						} else {
							PopupCommon.notify("error", res.data.message)
						}
					})
					.catch((err) => {
						PopupCommon.notify("error", err.message)
					})
			},
			submit(d) {
				let self = this
				console.log(d)
				if (d.id) {
					AjaxCommon("/ccdc/pm/em/filter/emFilterExaminee/edit", "post", d)
						.then((res) => {
							if (res.data.code == 200) {
								PopupCommon.notify("success", "操作成功")
								self.initPage()
								self.dialogClose()
							} else {
								PopupCommon.notify("error", res.data.message)
							}
						})
						.catch((err) => {
							PopupCommon.notify("error", err.message)
						})
				} else {
					delete d.id
					AjaxCommon("/ccdc/pm/em/filter/emFilterExaminee/add", "post", d)
						.then((res) => {
							if (res.data.code == 200) {
								PopupCommon.notify("success", "操作成功")
								self.initPage()
								self.dialogClose()
							} else {
								PopupCommon.notify("error", res.data.message)
							}
						})
						.catch((err) => {
							PopupCommon.notify("error", err.message)
						})
				}
			},
			dialogClose() {
				this.dialogShow = false
			},
			dialogBlackClose() {
				this.dialogBlackShow = false
			},
			dialogHisCodeClose() {
				this.hisCodeShow = false
			},
			searchClick() {
				this.pageNo = 1
				this.initPage()
			},
			setClick() {
				if (this.rightSelectIds.length == 1) {
					let formConfigItem = this.blackFormConfig
					formConfigItem.map((t) => {
						Object.keys(t).map((res) => {
							if (res == "fieldName") {
								if (
									t[res] != "blackTime" &&
									t[res] != "userName" &&
									t[res] != "examineeCode"
								) {
									t.filedValue = ""
								} else if (t[res] == "blackTime") {
									t.filedValue = Utility.getCurrentTime()
								} else if (t[res] == "userName") {
									t.filedValue = SessionCommon.getCurUserName()
								} else if (t[res] == "examineeCode") {
									t.filedValue = this.rightSelectIds[0].examineeCode
								}
							}
						})
					})
					this.blackFormConfig = formConfigItem
					this.dialogBlackShow = true
				} else {
					PopupCommon.notify("info", "请选择一个受试者")
				}
				// 设置黑名单
			},
			resetClick() {
				this.examineeName = ""
			},
			hisCodeClick() {
				this.hisCodeShow = true
			},
			addClick() {
				let formConfigItem = this.formConfig
				formConfigItem.map((t) => {
					Object.keys(t).map((res) => {
						if (res == "fieldName") {
							if (t[res] != "createByName") {
								t.filedValue = ""
							}
						}
					})
				})
				this.formConfig = formConfigItem
				this.type = "add"
				this.dialogShow = true
				this.dialogTitle =
					"新增" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title
			},
			// 分页点击事件
			pageChange(p) {
				this.pageNo = p
				this.initPage()
			},
			editRow(d) {
				this.type = "edit"
				let formConfigItem = this.formConfig
				formConfigItem.map((t) => {
					Object.keys(t).map((res) => {
						if (res == "fieldName") {
							t.filedValue = d.data[t[res]]
						}
					})
				})
				this.formConfig = formConfigItem
				this.dialogShow = true
				this.dialogTitle =
					"编辑" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title
			},
			viewRow(d) {
				this.type = "look"
				let formConfigItem = this.formConfig
				formConfigItem.map((t) => {
					Object.keys(t).map((res) => {
						if (res == "fieldName") {
							t.filedValue = d.data[t[res]]
						}
					})
				})
				this.formConfig = formConfigItem
				this.dialogShow = true
				this.dialogTitle =
					"查看" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title
			},
			deleteRow(d) {
				const id = d.data.id
				let self = this
				AjaxCommon(
					"/ccdc/pm/em/filter/emFilterExaminee/delete?id=" + id,
					"delete",
					{ optReason: d.optReason }
				).then((res) => {
					console.log(res, "res...............")
					if (res.data.code == 200) {
						PopupCommon.notify("success", "删除成功")
						self.initPage()
						self.dialogClose()
					} else {
						PopupCommon.notify("error", res.data.message)
					}
				})
			},
			// 初始化事件
			initPage() {
				let self = this
				AjaxCommon("/ccdc/pm/em/filter/emFilterExaminee/listByPage", "post", {
					examineeName: this.examineeName,
					pageNo: this.pageNo,
					pageSize: this.pageSize,
				}).then((res) => {
					if (res.data.code == 200) {
						self.dataSource = res.data.result.records
						self.pageCount = res.data.result.total
					} else {
						PopupCommon.notify("error", res.data.message)
					}
				})
			},
			// 初始化事件
			initConfig() {
				let self = this
				let projectTestperiod =
					window.sessionStorage.getItem("projectTestperiod")
				self.projectTestperiod = JSON.parse(projectTestperiod)
				console.log(projectTestperiod)
				AjaxCommon(
					"/ccdc/cfg/pm/pmExp/queryById?id=" + self.projectTestperiod.testId,
					"get"
				)
					.then((result) => {
						if (result.data.code == 200) {
							self.currentExp = result.data.result
						} else {
							PopupCommon.notify("error", result.data.message)
						}
					})
					.catch((e) => {
						console.log(e, "e.message")
					})
			},
		},
		mounted() {
			this.initPage()
			this.initConfig()
		},
	}
</script>

<style></style>
